<template>
  <div class="userMenu" style="padding: 0px 20px">
    <el-dropdown cursor: pointer v-show="isLogin">
      <span class="el-dropdown-link userMenu">
        {{ userName }}
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="navigateTo(userBackstageUrl)">个人后台</el-dropdown-item>
          <el-dropdown-item v-if="isManager" @click="navigateTo('/manager/info')">社长后台</el-dropdown-item>
          <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <a v-if="!isLogin"
       href="/login"
       class="not-login-container">
      未登录
    </a>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from "../../../stores/user.ts";
import {onMounted, ref} from "vue";
import USER_ROLE_ENUM from "../../../access/userRoleEnum.ts";
import {useRoute, useRouter} from "vue-router";
import {ElMessage} from "element-plus";

const store = useUserStore();
const userName = ref('')
const isLogin = ref(false);
const isManager = ref(false);
const userBackstageUrl = ref('/userBackground');

const initComponents = () => {
  if (!store.userName || store.userName === '') {
    userName.value = '未登录';
  } else {
    userName.value = store.userName;
  }

  if (store.userRole && store.userRole !== USER_ROLE_ENUM.NOT_LOGIN) {
    isLogin.value = true;
    if (store.userRole === USER_ROLE_ENUM.MANAGER){
      isManager.value = true;
    }
    if (store.userRole === USER_ROLE_ENUM.ADMIN) {
      userBackstageUrl.value = '/manage';
    }
  }
}

onMounted(() => {
  initComponents();
})

const router = useRouter();
const navigateTo = (path: string) => {
  router.push(path);
}

const handleLogout = async () => {
  try {
    await store.logout();
    ElMessage.success("登出成功");
    if (router.currentRoute.value.path === '/home') {
      window.location.reload()
    } else {
      router.push('/home');
      router.afterEach((to, from) => {
        if (to.path === '/home' && to.path !== from.path) {
          window.location.reload();
        }
      })
    }

  } catch (error) {
    ElMessage.error('登出失败：' + error)
  }
}
</script>

<style scoped lang="scss">
.userMenu {
  font-size: large;
  color: white;
  margin-right: 10px;
}
.not-login-container{
  color: white;
}
</style>
